﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <ToolboxData("<{0}:WhatsNewControl runat=server></{0}:WhatsNewControl>")> _
    Public Class WhatsNewControl
        Inherits DotNetNuke.Entities.Modules.PortalModuleBase

        Private _forumIds As String = String.Empty
        Private _topicsOnly As Boolean = True
        Private _randomOrder As Boolean = False
        Private _rows As Integer = 10
        Private _tags As String = String.Empty
        Private _filterByUserId As Integer = -1
        Private _whatsNewTemplate As DisplayTemplate
        Private _headerTemplate As DisplayTemplate
        Private _footerTemplate As DisplayTemplate
        Private _allowRSS As Boolean
        Private _tabId As Integer = -1
        Private _additionalParams As String = String.Empty
        Public Property AdditionalParams() As String
            Get
                Return _additionalParams
            End Get
            Set(ByVal value As String)
                _additionalParams = value
            End Set
        End Property

        Public Overloads Property TabId() As Integer
            Get
                Return _tabId
            End Get
            Set(ByVal value As Integer)
                _tabId = value
            End Set
        End Property
        Public Property ForumIds() As String
            Get
                Return _forumIds
            End Get
            Set(ByVal value As String)
                _forumIds = value
            End Set
        End Property
        Public Property TopicsOnly() As Boolean
            Get
                Return _topicsOnly
            End Get
            Set(ByVal value As Boolean)
                _topicsOnly = value
            End Set
        End Property
        Public Property RandomOrder() As Boolean
            Get
                Return _randomOrder
            End Get
            Set(ByVal value As Boolean)
                _randomOrder = value
            End Set
        End Property
        Public Property Rows() As Integer
            Get
                Return _rows
            End Get
            Set(ByVal value As Integer)
                _rows = value
            End Set
        End Property
        Public Property Tags() As String
            Get
                Return _tags
            End Get
            Set(ByVal value As String)
                _tags = value
            End Set
        End Property
        Public Property FilterByUserId() As Integer
            Get
                Return _filterByUserId
            End Get
            Set(ByVal value As Integer)
                _filterByUserId = value
            End Set
        End Property
        <Description("Template for display"), PersistenceMode(PersistenceMode.InnerProperty)> _
            Public Property Template() As DisplayTemplate
            Get
                Return _whatsNewTemplate
            End Get
            Set(ByVal Value As DisplayTemplate)
                _whatsNewTemplate = Value
            End Set
        End Property
        <Description("Template for display"), PersistenceMode(PersistenceMode.InnerProperty)> _
    Public Property HeaderTemplate() As DisplayTemplate
            Get
                Return _headerTemplate
            End Get
            Set(ByVal Value As DisplayTemplate)
                _headerTemplate = Value
            End Set
        End Property
        <Description("Template for display"), PersistenceMode(PersistenceMode.InnerProperty)> _
    Public Property FooterTemplate() As DisplayTemplate
            Get
                Return _footerTemplate
            End Get
            Set(ByVal Value As DisplayTemplate)
                _footerTemplate = Value
            End Set
        End Property
        Public Property EnableRSS() As Boolean
            Get
                Return _allowRSS
            End Get
            Set(ByVal value As Boolean)
                _allowRSS = False
            End Set
        End Property
        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            'If TabId = -1 Then
            '    TabId = CInt(Request.QueryString("TabId"))
            'End If
            Dim timeOffset As Integer = 0
            timeOffset = PortalSettings.TimeZoneOffset
            If UserId > 0 Then
                Dim uc As New DotNetNuke.Entities.Users.UserController
                Dim dnnUser As DotNetNuke.Entities.Users.UserInfo = uc.GetUser(PortalId, UserId)
                timeOffset = dnnUser.Profile.TimeZone
                If timeOffset = 0 Then
                    timeOffset = PortalSettings.TimeZoneOffset
                End If
            End If
            
            Dim sHeaderTemplate As String = "<div style=""padding:10px;padding-top:5px;"">"
            Dim sFooterTemplate As String = "</div>"
            If Not HeaderTemplate Is Nothing Then
                sHeaderTemplate = HeaderTemplate.Text
            End If
            If Not FooterTemplate Is Nothing Then
                sFooterTemplate = FooterTemplate.Text
            End If
            Dim sTemplate As String = "<div style=""padding-bottom:2px;"" class=""normal"">[SUBJECTLINK]</div><div style=""padding-bottom:2px;border-bottom:solid 1px #AAA;"">by [AUTHORDISPLAYNAME]</div>"
            If Not Template Is Nothing Then
                sTemplate = Template.Text
            End If
            If Not ForumIds = String.Empty Or FilterByUserId > 0 Then
                If ForumIds.Contains(";") Then
                    ForumIds = ForumIds.Replace(";", ":")
                End If
                Dim sb As New StringBuilder(1024)
                sb.Append(sHeaderTemplate)
                Dim BodyLength As Integer = -1
                Dim BodyTrim As String = ""
                If sTemplate.Contains("[BODY:") Then
                    Dim inStart As Integer = InStr(sTemplate, "[BODY:") + 5
                    Dim inEnd As Integer = InStr(inStart, sTemplate, "]") - 1
                    Dim sLength As String = sTemplate.Substring(inStart, inEnd - inStart)
                    BodyLength = CType(sLength, Integer)
                    BodyTrim = "[BODY:" & BodyLength.ToString & "]"
                End If
                Dim dr As IDataReader
                If ForumIds = String.Empty And FilterByUserId > 0 Then
                    Dim fc As New ForumController
                    Dim uc As New UserController
                    Dim u As User = uc.DNNGetCurrentUser(PortalId, -1)
                    ForumIds = fc.GetForumsForUser(u.UserRoles, PortalId, -1)
                    ForumIds = ForumIds.Replace(";", ":")
                    dr = DataProvider.Instance.GetPostsByUser(PortalId, Rows, UserInfo.IsSuperUser, UserInfo.UserID, FilterByUserId, TopicsOnly, ForumIds)
                Else
                    dr = DataProvider.Instance.GetPosts(PortalId, ForumIds, TopicsOnly, RandomOrder, Rows, UserId, False, UserInfo.IsSuperUser, Tags, FilterByUserId)
                End If
                Dim useFriendly As Boolean = Utilities.IsRewriteLoaded
                Dim sHost As String = Utilities.GetHost()
                Try
                    While dr.Read()
                        Dim sTempTemplate As String = sTemplate
                        Dim GroupName As String = String.Empty
                        Dim GroupId As String = String.Empty
                        Dim TopicTabId As String = String.Empty
                        Dim TopicModuleId As String = String.Empty
                        Dim ForumName As String = String.Empty
                        Dim ForumId As String = String.Empty
                        Dim Subject As String = String.Empty
                        Dim UserName As String = String.Empty
                        Dim PostDate As String = String.Empty
                        Dim Body As String = String.Empty
                        Dim BodyHTML As String = String.Empty
                        Dim DisplayName As String = String.Empty
                        Dim ReplyCount As String = String.Empty
                        Dim LastPostDate As String = String.Empty
                        Dim TopicId As String = String.Empty
                        Dim ReplyId As String = String.Empty
                        Dim FirstName As String = String.Empty
                        Dim LastName As String = String.Empty
                        Dim AuthorId As String = String.Empty
                        Dim sForumUrl As String = String.Empty
                        Dim sTopicURL As String = String.Empty
                        Dim sGroupPrefixURL As String = String.Empty

                        GroupName = CStr(dr("GroupName"))
                        GroupId = CStr(dr("ForumGroupId"))
                        TopicTabId = CStr(dr("TabId"))
                        TopicModuleId = CStr(dr("ModuleId"))
                        ForumName = CStr(dr("ForumName"))
                        ForumId = CStr(dr("ForumId"))
                        Subject = CStr(dr("Subject"))
                        UserName = CStr(dr("AuthorUserName"))
                        FirstName = CStr(dr("AuthorFirstName"))
                        LastName = CStr(dr("AuthorLastName"))
                        AuthorId = CStr(dr("AuthorId"))
                        DisplayName = CStr(dr("AuthorDisplayName"))
                        PostDate = CStr(dr("DateCreated"))
                        Body = Utilities.StripHTMLTag(CStr(dr("Body")))
                        TopicId = CStr(dr("TopicId"))
                        ReplyId = CStr(dr("ReplyId"))
                        BodyHTML = CStr(dr("Body"))
                        ReplyCount = CStr(dr("ReplyCount"))
                        sForumUrl = dr("PrefixURL").ToString
                        sTopicURL = dr("TopicURL").ToString
                        sGroupPrefixURL = dr("GroupPrefixURL").ToString
                        sTempTemplate = sTempTemplate.Replace("[FORUMGROUPNAME]", GroupName)
                        sTempTemplate = sTempTemplate.Replace("[FORUMGROUPID]", GroupId)
                        sTempTemplate = sTempTemplate.Replace("[TOPICTABID]", TopicTabId)
                        sTempTemplate = sTempTemplate.Replace("[TOPICMODULEID]", TopicModuleId)
                        sTempTemplate = sTempTemplate.Replace("[FORUMNAME]", ForumName)
                        sTempTemplate = sTempTemplate.Replace("[FORUMID]", ForumId)
                        sTempTemplate = sTempTemplate.Replace("[SUBJECT]", Subject)
                        sTempTemplate = sTempTemplate.Replace("[AUTHORUSERNAME]", UserName)
                        sTempTemplate = sTempTemplate.Replace("[AUTHORFIRSTNAME]", FirstName)
                        sTempTemplate = sTempTemplate.Replace("[AUTHORLASTNAME]", LastName)
                        sTempTemplate = sTempTemplate.Replace("[AUTHORID]", AuthorId)
                        sTempTemplate = sTempTemplate.Replace("[AUTHORDISPLAYNAME]", DisplayName)
                        sTempTemplate = sTempTemplate.Replace("[DATE]", Utilities.GetDate(CDate(PostDate), CInt(TopicModuleId), timeOffset))
                        sTempTemplate = sTempTemplate.Replace("[BODY]", Body)
                        sTempTemplate = sTempTemplate.Replace("[BODYHTML]", BodyHTML)
                        sTempTemplate = sTempTemplate.Replace("[BODYTEXT]", Utilities.StripHTMLTag(BodyHTML))
                        If Not BodyTrim = String.Empty Then
                            If BodyLength > 0 And Body.Length > BodyLength Then
                                sTempTemplate = sTempTemplate.Replace(BodyTrim, Body.Substring(0, BodyLength) & "...")
                            Else
                                sTempTemplate = sTempTemplate.Replace(BodyTrim, Body)
                            End If
                        End If

                        sTempTemplate = sTempTemplate.Replace("[TOPICID]", TopicId)
                        sTempTemplate = sTempTemplate.Replace("[REPLYID]", ReplyId)
                        sTempTemplate = sTempTemplate.Replace("[REPLYCOUNT]", ReplyCount)

                        If TabId = -1 Then
                            TabId = CInt(TopicTabId)
                        End If
                        If useFriendly And Not String.IsNullOrEmpty(sForumUrl) And Not String.IsNullOrEmpty(sTopicURL) Then
                            Dim ctlUtils As New ControlUtils
                            sTopicURL = ctlUtils.BuildUrl(CInt(TopicTabId), CInt(TopicModuleId), sGroupPrefixURL, sForumUrl, CInt(GroupId), CInt(ForumId), CInt(TopicId), sTopicURL, -1, -1, String.Empty, 1, -1)

                            'If sHost.EndsWith("/") And sForumUrl.StartsWith("/") Then
                            '    sForumUrl = sForumUrl.Substring(1)
                            'End If
                            'sForumUrl = sHost & sForumUrl
                            'If sHost.EndsWith("/") And sTopicURL.StartsWith("/") Then
                            '    sTopicURL = sTopicURL.Substring(1)
                            'End If
                            'sTopicURL = sHost & sTopicURL
                            If CInt(ReplyId) = 0 Then
                                sTempTemplate = sTempTemplate.Replace("[POSTURL]", sTopicURL)
                                sTempTemplate = sTempTemplate.Replace("[SUBJECTLINK]", "<a href=""" & sTopicURL & """>" & Subject & "</a>")
                            Else
                                If Not sTopicURL.EndsWith("/") Then
                                    sTopicURL &= "/"
                                End If
                                sTopicURL &= "?afc=" & ReplyId
                                sTempTemplate = sTempTemplate.Replace("[POSTURL]", sTopicURL)
                                If Request.IsAuthenticated Then
                                    sTempTemplate = sTempTemplate.Replace("[SUBJECTLINK]", "<a href=""" & sTopicURL & """>" & Subject & "</a>")
                                Else
                                    sTempTemplate = sTempTemplate.Replace("[SUBJECTLINK]", "<a href=""" & sTopicURL & """ rel=""nofollow"">" & Subject & "</a>")
                                End If
                            End If
                            sTempTemplate = sTempTemplate.Replace("[TOPICSURL]", sForumUrl)

                        Else
                            Dim params() As String
                            If CInt(ReplyId) = 0 Then
                                params = New String() {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId}
                                If Not AdditionalParams = String.Empty Then
                                    params = Utilities.AddParams(AdditionalParams, params)
                                End If
                                sTempTemplate = sTempTemplate.Replace("[POSTURL]", Utilities.NavigateUrl(TabId, "", params))
                                params = New String() {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId}
                                If Not AdditionalParams = String.Empty Then
                                    params = Utilities.AddParams(AdditionalParams, params)
                                End If
                                sTempTemplate = sTempTemplate.Replace("[SUBJECTLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", params) & """>" & Subject & "</a>")
                            Else
                                params = New String() {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId}
                                If Not AdditionalParams = String.Empty Then
                                    params = Utilities.AddParams(AdditionalParams, params)
                                End If
                                sTempTemplate = sTempTemplate.Replace("[POSTURL]", Utilities.NavigateUrl(TabId, "", params))
                                params = New String() {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & ReplyId}
                                If Not AdditionalParams = String.Empty Then
                                    params = Utilities.AddParams(AdditionalParams, params)
                                End If
                                sTempTemplate = sTempTemplate.Replace("[SUBJECTLINK]", "<a href=""" & Utilities.NavigateUrl(TabId, "", params) & """>" & Subject & "</a>")
                            End If
                            params = New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & ForumId}
                            If Not AdditionalParams = String.Empty Then
                                params = Utilities.AddParams(AdditionalParams, params)
                            End If
                            sTempTemplate = sTempTemplate.Replace("[TOPICSURL]", Utilities.NavigateUrl(TabId, "", params))

                        End If
                        sTempTemplate = sTempTemplate.Replace("[FORUMURL]", Utilities.NavigateUrl(TabId))
                        sb.Append(sTempTemplate)
                        'sb.Append("<div class=""astopicsubject""><a href=""" & Utilities.NavigateUrl(CInt(TopicTabId), "", New String() {ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId}) & """>" & Subject & "</a> in " & ForumName & "</div>")
                        'If Body.Length > 150 Then
                        '    Body = Body.Substring(0, 150)
                        'End If
                        'sb.Append("<div class=""astopicbody"">" & Body & "</div>")
                    End While
                    dr.Close()
                    Dim sRSSImage As String = String.Empty
                    Dim sRSSURL As String = String.Empty
                    Dim sRSSIconLink As String = String.Empty

                    sRSSImage = "<img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/images/feedicon.gif") & """ border=""0"" />"
                    sRSSURL = Page.ResolveUrl("~/desktopmodules/activeforumswhatsnew/feeds.aspx") & "?portalId=" & PortalId & "&tabid=" & TabId.ToString & "&moduleid=" & ModuleId.ToString
                    sRSSIconLink = "<a href=""" & sRSSURL & """>" & sRSSImage & "</a>"
                    sFooterTemplate = sFooterTemplate.Replace("[RSSICON]", sRSSImage)
                    sFooterTemplate = sFooterTemplate.Replace("[RSSURL]", sRSSURL)
                    sFooterTemplate = sFooterTemplate.Replace("[RSSICONLINK]", sRSSIconLink)

                    sb.Append(sFooterTemplate)
                    Dim lit As New Literal
                    lit.Text = sb.ToString
                    Me.Controls.Add(lit)

                Catch ex As Exception
                    If Not dr.IsClosed Then
                        dr.Close()
                    End If
                    sb.Append(ex.StackTrace)
                    Dim lit As New Literal
                    lit.Text = ex.Message
                    Me.Controls.Add(lit)
                End Try

            End If

        End Sub

    End Class
End Namespace
